package com.eastcom.collection.provider

import java.net.MalformedURLException;
import java.rmi.AccessException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.Remote
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;
@Component("rmiProvider")
@Scope("prototype")
public class RmiServiceProvider  extends Thread {
	static Log logger = LogFactory.getLog(RmiServiceProvider.class);
	String rmiServiceAddr;
	int rmiServicePort;
	String rmiServiceName;
	boolean isRunning;
	String rmiUrl;
	Remote resource
	byte[] waitObject = new byte[0];
	Registry registry;
	@Override
	public synchronized void start() {
		// TODO 自动生成的方法存根
		super.start();
	}

	@Override
	public void run() {
		try {
			registry=LocateRegistry.createRegistry(rmiServicePort);
			rmiUrl="rmi://" + rmiServiceAddr + ":" + rmiServicePort	+ "/"+rmiServiceName;
			Naming.rebind(rmiUrl, resource);
			logger
			.info("Server bind in registry: "
					+ "URL="
					+ rmiServiceAddr
					+ ",Port="
					+ rmiServicePort
					+ ",Service="+rmiServiceName);
			System.out.println("Server bind in registry: "
					+ "URL="
					+ rmiServiceAddr
					+ ",Port="
					+ rmiServicePort
					+ ",Service="+rmiServiceName);
			logger.info("rmi["+resource+"]绑定到服务......");
			while(isRunning){
				synchronized (waitObject) {
					try{
						waitObject.wait();
					}catch(InterruptedException e){
						logger.warn(e);
					}
				}
			}
		} catch (Exception ex) {
			logger.error(ex.getLocalizedMessage());
			ex.printStackTrace();
			System.exit(-1);
		}


	}
	@PreDestroy
	public void shutdown() {
		try {
			Naming.unbind(rmiUrl);
			registry.unbind(rmiServiceName);
			UnicastRemoteObject.unexportObject(registry, true);
		} catch (MalformedURLException e) {
			logger.error(e);
		} catch (AccessException e) {
			logger.error(e);
		} catch (RemoteException e) {
			logger.error(e);
		} catch (NotBoundException e) {
			logger.error(e);
		}finally{
			isRunning=false;
			synchronized (waitObject) {
				waitObject.notifyAll();
			}
		}
	}
}